<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 详情接口
 *
 * @author      Eden
 * @datetime    2016/12/1 22:56
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Detail_Model extends ADM_Model
{

    // 参数
    private $params;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取详情
     * @param array $params
     * @return array|bool
     */
    public function getOrderDetail(Array $params)
    {
        $this->params = $params;

        if (!$this->checkParams()) {
            return false;
        }

        $detail = $this->getDetail();
        if (!$detail) {
            return false;
        }

        /*
        if ($detail['status'] == 'Unpaid') {

        }
        */

        $detail['addressInfo'] = $this->getAddress($detail['addressId']);
        return $detail;
    }

    /**
     * 获取收货人信息
     * @param $addressId
     * @return array
     */
    protected function getAddress($addressId)
    {
        $add = array(
            'name' => '',
            'phone' => '',
            'address' => ''
        );
        if (empty($addressId)) {
            return $add;
        }

        $addDb = clone($this->db);
        $query = $addDb->get_where('user_address', array('id' => $addressId));
        $result = $query->row_array();
        if (!$result) {
            return $add;
        }

        $add['name'] = value($result, 'name');
        $add['phone'] = value($result, 'phone');
        $add['address'] = sprintf('%s %s %s', $result['province'], $result['city'], $result['area']);
        $add['area'] = value($result, 'address');
        return $add;
    }

    /**
     * 商品详情
     * @return array|bool
     */
    protected function getDetail()
    {
        $orderId = $this->params['orderId'];
        try {
            $orderDb = clone($this->db);
            $query = $orderDb->get_where('user_order', array('id' => $orderId));
            $row = $query->row_array();
            if (empty($row)) {
                $this->setError('该订单不存在');
                return false;
            }

            $goodsDb = clone($this->db);
            $query = $goodsDb->select('uog.num, uog.price, uog.orderId, uog.goodsId, sg.goodsName, sg.baseId, sg.thumb,
            r.name as ruleName, sg.status')
                ->where_in('uog.orderId', $orderId)
                ->from('user_order_goods as uog')
                ->join('base_goods as sg', 'sg.id = uog.goodsId')
                ->join('base_goods_rule as r', 'r.id=uog.ruleId')
                ->get();
            $results = $query->result_array();
            $this->load->library('core/upload', null, 'up');
            $items = array();
            if ($results && is_array($results)) foreach($results as $item) {
                $thumb = thumb($item['thumb']);
                $goodsItem = array(
                    'goodsId' => (int) value($item, 'goodsId'),
                    'goodsName' => value($item, 'goodsName'),
                    'num' => (int) value($item, 'num'),
                    'price' => money_format('%i', $item['price'] / 100),
                    'thumb' => $thumb ? $thumb : "",
                    'itemTotal' => money_format('%i', $item['price'] * $item['num'] / 100),
                    'status' => (int) $item['status'],
                    'ruleName' => value($item, 'ruleName', '')
                );
                $items[] = $goodsItem;
            }

            $goods = $row;
            $returns = array();
            $returns['orderId'] = (int) $goods['id'];
            $returns['sn'] = value($goods, 'sn');
            $returns['totalPrice'] = money_format('%i', $goods['totalPrice'] / 100);
            $returns['goodsPrice'] = money_format('%i', $goods['goodsPrice'] / 100);
            $returns['expressPrice'] = money_format('%i', $goods['expressPrice'] / 100);
            $returns['voucherPrice'] = money_format('%i', $this->getVoucherPrice($goods['userId'], $goods['voucher']) / 100);
            $returns['addressId'] = (int) value($goods, 'addressId');
            $returns['payMode'] = value($goods, 'payMode');
            $returns['payWay'] = value($goods, 'payWay');
            $returns['created'] = value($goods, 'created');
            $returns['distribution'] = $this->getExpress($orderId);
            $returns['status'] = value($goods, 'status');
            $returns['goods'] = $items;
            $returns['message'] = value($goods, 'message', '');

            return $returns;

        } catch (PDOException $e) {
            $this->setError('订单获取失败');
        }
        return false;
    }

    /**
     * 代金券价格
     * @param $userId
     * @param string $voucher
     * @return float|int
     */
    private function getVoucherPrice($userId, $voucher = '')
    {
        if (empty($voucher) || empty($userId)) {
            return 0;
        }

        $db = clone($this->db);
        $q = $db->select('money')->get_where('user_voucher', array('userId' => $userId, 'voucher' => $voucher));
        $row = $q->row_array();
        if (empty($row)) {
            return 0;
        }

        return doubleval($row['money']);
    }

    /**
     * 快递
     * @param $orderId
     * @return mixed
     */
    public function getExpress($orderId)
    {
        $return['expressNo'] = '';
        $return['expressName'] = '';
        $return['expressTime'] = '';
        $query = $this->db->get_where('user_order_express', array('orderId' => $orderId));
        $row = $query->row_array();
        if ($row) {
            $return['expressNo'] = value($row, 'expressNo');
            $return['expressName'] = value($row, 'expressName');
            $return['expressTime'] = value($row, 'created');
        }
        return $return;
    }

    /**
     * 验证参数
     * @return bool
     */
    public function checkParams()
    {
        if (empty($this->params['orderId'])){
            $this->setError('参数错误');
            return false;
        }
        return true;
    }

    public function setRefund($orderId, $type, $amount = 0)
    {
        $odb = clone($this->db);
        $orderQuery = $odb->get_where('user_order', ['id' => $orderId]);
        $order = $orderQuery->row_array();
        if (empty($order) || empty($order['goodsPrice'])) {
            return false;
        }

        $udb = clone($this->db);
        $cashdb = clone($this->db);
        $note = '';
        switch($type) {
            case 1:
                $amount = $order['goodsPrice'];
                $udb->set('amount', "amount+{$amount}", false);
                $udb->set('amountUnLimit', "amountUnLimit+{$amount}", false);
                $udb->where('id', $order['userId']);
                if (!$udb->update('user')) {
                    return false;
                }
                $note = '全额退款';
                break;
            case 2:
                $amount = $order['goodsPrice'];
                $unlimit = ceil($amount * 0.7);
                $limit = $amount - $unlimit;
                $udb->set("amount", "amount+{$amount}");
                $udb->set("amountUnLimit", "amountUnLimit+{$unlimit}");
                $udb->set("amountBuy", "amountBuy+{$limit}");
                $udb->where('id', $order['userId']);
                if (!$udb->update('user')) {
                    return false;
                }
                $note = '活动退款';
                break;
            case 3:
                if ($amount > $order['goodsPrice']) {
                    return false;
                }
                $udb->set('amount', "amount+{$amount}", false);
                $udb->set('amountUnLimit', "amountUnLimit+{$amount}", false);
                $udb->where('id', $order['userId']);
                if (!$udb->update('user')) {
                    return false;
                }
                $note = '指定金额退款';
                break;
            default:
                return;
        }

        $odb->where('id', $order['id']);
        $odb->update('user_order', [
            'status' => 'Refunded',
            'compTime' => dateTime(),
        ]);

        $rdb = clone($this->db);
        $rdb->where('orderId', $order['id']);
        $rdb->update('user_order_refund', [
            'adminId' => adminId(),
            'refundAmount' => $amount,
            'actualAmount' => $order['goodsPrice'],
            'remark' => $note,
            'handleTime' => dateTime(),
            'status' => '6'
        ]);

        $cashdb->insert("user_cash_record", [
            'userid' => $order['userId'],
            'type' => 'refund',
            'created' => dateTime(),
            'amount' => $amount,
            'note' => $note
        ]);

        return $cashdb->insert_id();
    }
}
